import React, { useState, useEffect } from 'react';
import {
  Typography,
  Card,
  Table,
  Button,
  Space,
  Tag,
  Progress,
  message,
  Row,
  Col,
  Statistic,
  Input,
  Select,
  DatePicker,
  Tooltip,
  Popconfirm,
  Empty,
  Spin,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  TeamOutlined,
  CalendarOutlined,
  TrophyOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';

// 导入子组件
import CreateActivity from './CreateActivity';
import EditActivity from './EditActivity';
import ActivityDetail from './ActivityDetail';
import ParticipantManagement from './ParticipantManagement';

// 导入API和常量
import {
  getCheckinActivitiesApi,
  deleteCheckinActivityApi,
  getCheckinStatsApi,
} from '../../../api/checkin';
import {
  CHECKIN_STATUS_OPTIONS,
  getStatusColor,
  DEFAULTS,
} from '../CheckType';

const { Title } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const ActivityManagement = () => {
  // 状态管理
  const [activities, setActivities] = useState([]);
  const [stats, setStats] = useState({});
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    keywords: '',
    status: undefined,
    dateRange: undefined,
  });
  
  // 分页状态管理
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: DEFAULTS.PAGE_SIZE,
    total: 0,
  });

  // 模态框状态
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isParticipantModalVisible, setIsParticipantModalVisible] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState(null);

  // 获取当前用户ID
  const getCurrentUserId = () => 1; // 临时写死，实际应该从登录状态获取

  // 组件挂载时获取数据
  useEffect(() => {
    fetchActivities();
    fetchStats();
  }, []);

  // 获取打卡活动列表
  const fetchActivities = async (params) => {
    try {
      setLoading(true);
      const response = await getCheckinActivitiesApi({
        ...params,
        pageNum: params?.pageNum || pagination.current,
        pageSize: params?.pageSize || pagination.pageSize,
      });
      if (response && response.code === '0') {
        setActivities(response.data?.list || []);
        setPagination(prev => ({ ...prev, total: response.data?.total || 0 }));
      } else {
        message.error(response.msg || '获取活动列表失败');
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      message.error('获取活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const response = await getCheckinStatsApi({
        userId: getCurrentUserId()
      });
      
      if (response && response.code === '0') {
        setStats(response.data || {});
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    }
  };

  // 处理搜索
  const handleSearch = () => {
    // 构建搜索参数，将时间区间拆分为开始和结束时间
    const params = {
      ...searchParams,
      startDate: searchParams.dateRange?.[0]?.format('YYYY-MM-DD'),
      endDate: searchParams.dateRange?.[1]?.format('YYYY-MM-DD'),
    };

    // 移除dateRange字段，避免传递给后端
    delete params.dateRange;

    // 重置分页到第一页
    setPagination(prev => ({ ...prev, current: 1 }));

    fetchActivities(params);
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({
      keywords: '',
      status: undefined,
      dateRange: undefined,
    });

    // 重置分页到第一页
    setPagination(prev => ({ ...prev, current: 1 }));

    fetchActivities();
  };

  // 处理分页变化
  const handleTableChange = (paginationInfo) => {
    setPagination(paginationInfo);
    fetchActivities({
      pageNum: paginationInfo.current,
      pageSize: paginationInfo.pageSize,
    });
  };

  // 处理操作成功回调
  const handleOperationSuccess = () => {
    fetchActivities();
    fetchStats();
    // 关闭所有模态框
    setIsCreateModalVisible(false);
    setIsEditModalVisible(false);
    setIsDetailModalVisible(false);
    setIsParticipantModalVisible(false);
  };

  // 处理查看详情
  const handleViewDetail = (activity) => {
    setSelectedActivity(activity);
    setIsDetailModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (activity) => {
    setSelectedActivity(activity);
    setIsEditModalVisible(true);
  };

  // 处理删除
  const handleDelete = async (activity) => {
    try {
      const response = await deleteCheckinActivityApi({
        id: activity.id,
        userId: getCurrentUserId()
      });
      
      if (response && response.code === '0') {
        message.success('删除成功');
        handleOperationSuccess();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 处理参与者管理
  const handleParticipantManagement = (activity) => {
    setSelectedActivity(activity);
    setIsParticipantModalVisible(true);
  };

  // 表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 500, marginBottom: 4 }}>{text}</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            {record.description && record.description.length > 50 
              ? `${record.description.substring(0, 50)}...` 
              : record.description}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {CHECKIN_STATUS_OPTIONS.find(s => s.value === status)?.label || '未知'}
        </Tag>
      ),
    },
    {
      title: '时间范围',
      key: 'dateRange',
      width: 200,
      render: (_, record) => (
        <div>
          <div>{dayjs(record.startDate).format('YYYY-MM-DD')}</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            至 {dayjs(record.endDate).format('YYYY-MM-DD')}
          </div>
        </div>
      ),
    },
    {
      title: '目标天数',
      dataIndex: 'targetDays',
      key: 'targetDays',
      width: 100,
      render: (days) => `${days} 天`,
    },
    {
      title: '参与人数',
      dataIndex: 'totalParticipants',
      key: 'totalParticipants',
      width: 100,
      render: (count) => (
        <Statistic value={count} suffix="人" valueStyle={{ fontSize: 14 }} />
      ),
    },
    {
      title: '进度',
      key: 'progress',
      width: 150,
      render: (_, record) => {
        const progress = record.targetDays ? Math.round(((record.completedDays || 0) / record.targetDays) * 100) : 0;
        return (
          <div>
            <Progress 
              percent={progress} 
              size="small" 
              status={progress >= 100 ? 'success' : 'active'}
            />
            <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
              {record.completedDays || 0}/{record.targetDays || 0} 天
            </div>
          </div>
        );
      },
    },
    {
      title: '创建人',
      dataIndex: 'createdByName',
      key: 'createdByName',
      width: 100,
      render: (text) => text || '未知用户',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="参与者管理">
            <Button
              type="text"
              icon={<TeamOutlined />}
              onClick={() => handleParticipantManagement(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个活动吗？"
            description="删除后无法恢复，请谨慎操作。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: 24 }}>
        <Title level={2} style={{ margin: 0 }}>
          <CalendarOutlined style={{ marginRight: 8 }} />
          打卡活动管理
        </Title>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总活动数"
              value={stats.totalActivities || 0}
              prefix={<CalendarOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="进行中"
              value={stats.activeActivities || 0}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总打卡天数"
              value={stats.totalCheckinDays || 0}
              suffix="天"
              prefix={<CalendarOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="完成率"
              value={stats.completionRate || 0}
              suffix="%"
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和操作区域 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Search
              placeholder="搜索活动名称或描述"
              value={searchParams.keywords}
              onChange={(e) => setSearchParams(prev => ({ ...prev, keywords: e.target.value }))}
              onSearch={handleSearch}
              enterButton
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="活动状态"
              value={searchParams.status}
              onChange={(value) => setSearchParams(prev => ({ ...prev, status: value }))}
              style={{ width: '100%' }}
              allowClear
            >
              {CHECKIN_STATUS_OPTIONS.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              value={searchParams.dateRange}
              onChange={(dates) => setSearchParams(prev => ({ ...prev, dateRange: dates }))}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Space>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleResetSearch}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
        
        <div style={{ marginTop: 16, textAlign: 'right' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setIsCreateModalVisible(true)}
          >
            创建活动
          </Button>
        </div>
      </Card>

      {/* 活动列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={activities}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
          locale={{
            emptyText: (
              <Empty
                description="暂无活动数据"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            ),
          }}
        />
      </Card>

      {/* 模态框组件 */}
      <CreateActivity
        visible={isCreateModalVisible}
        onCancel={() => setIsCreateModalVisible(false)}
        onSuccess={handleOperationSuccess}
      />

      <EditActivity
        visible={isEditModalVisible}
        activity={selectedActivity}
        onCancel={() => setIsEditModalVisible(false)}
        onSuccess={handleOperationSuccess}
      />

      <ActivityDetail
        visible={isDetailModalVisible}
        activity={selectedActivity}
        onCancel={() => setIsDetailModalVisible(false)}
      />

      <ParticipantManagement
        visible={isParticipantModalVisible}
        mainActivity={selectedActivity}
        onCancel={() => setIsParticipantModalVisible(false)}
        onSuccess={handleOperationSuccess}
      />
    </div>
  );
};

export default ActivityManagement;